using System;
using System.Collections.Generic;
using UnityEngine;

namespace EventBehaviorTree
{
    [Serializable]
    public class Sequencer : Container
    {
        public Sequencer() : base() { }
        public Sequencer(KeyValuePair<NodeMsg, NodeMsg>[] msgPairs, params NodeMsg[] silencedMsg) :
            base(msgPairs, silencedMsg)
        { }

        public override void NodeEvent(NodeMsg nodeMsg)
        {
            switch (nodeMsg)
            {
                case NodeMsg.Start:
                    if (!_isWorking)
                    {
                        SendMessage(nodeMsg);
                        _isWorking = true;
                        _stepCount = 0;
                        _subNodes[0].NodeEvent(nodeMsg);
                    }
                    break;
                case NodeMsg.Succeed:
                    if (_stepCount < _subNodes.Count - 1)
                    {
                        _subNodes[++_stepCount].NodeEvent(NodeMsg.Start);
                        return;
                    }
                    SendMessage(nodeMsg);
                    break;
                case NodeMsg.Fail:
                case NodeMsg.REQ_Abort:
                    StopAllSubNodes();
                    _isWorking = false;
                    SendMessage(nodeMsg);
                    break;
                case NodeMsg.CMD_Stop:
                    if (_isWorking)
                    {
                        StopAllSubNodes();
                        _isWorking = false;
                    }
                    break;
                default:
                    break;
            }
        }
    }
}
